<?php
declare (strict_types = 1);

namespace app\admin\controller;


use app\BaseController;
use think\facade\Db;
use think\Validate;

class Login extends BaseController
{
    // 登录页面
    public function index()
    {
        return view();
    }

    // 登录
    public function login()
    {
//        if ($this->request->isAjax()){
//            halt(input('post.'));
//        }

        $name   = input('name');
        $pw     = md5(input('password',''));
        $verify = input('verify');
        if ( !captcha_check($verify)){
            return err('验证码不正确');
        }
        $rules = [
            'name|账号' => 'require|max:11',
            'pw|密码' => 'require',
        ];
        $validate = new Validate($rules);
        $data   = [
            'name'   => $name,
            'pw'     => $pw,
        ];
        if (!$validate->check($data)) {
            return err($validate->getError());
        }
        $map['name'] = $name;
        $login = Db::name('admin')->where($map)->find();
        //密码连续错误超过3次
        $time = time();
        $err_time = $time - $login['err_time'];
        if ($err_time < '3600') {
            if ($login['num'] >= '3') {
                return err('密码连续错误3次，禁止1小时');
            }
        }
        if ($login) {
            if ($login['pw'] == $pw) {

                if ($login['state'] == '0') {
                    session('admin',$login);
                    session('name', $login['name']);
                    session('uid', $login['id']);
                    Db::name('admin')->where($map)->update(['num' => 0, 'login_ip' => $_SERVER['REMOTE_ADDR'], 'login_time' => date('Y-m-d h:i:s', time())]);
                    return suc('登录成功');
                } else {
                    return err('账号被禁用');
                }
            } else {
                $num = $login['num'] + 1;
                Db::name('admin')->where($map)->update(['num' => $num, 'err_time' => $time]);
                return err('密码错误' . $num . '次，连续错误3次，禁止1小时');
            }
        } else {
            return err('账号不存在');
        }


    }

    // 退出登录
    public function logout()
    {
        if  (session('admin') ) {
            session('uid', null);
            session('name', null);
        }
       $this->success('退出成功!','index');
    }


}
